#!/bin/bash

# SSL 证书自动更新脚本
# 适用于 CentOS 8 + Nginx 环境
# 作者: SSL 自动更新系统
# 版本: 1.0

# 配置变量
# 获取脚本所在目录的绝对路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG_FILE="$SCRIPT_DIR/logs/ssl_renewal.log"
ERROR_LOG="$SCRIPT_DIR/logs/ssl_errors.log"
DOMAINS_FILE="$SCRIPT_DIR/domains.conf"
EMAIL="605600162@qq.com"  # 请修改为您的邮箱
WEBROOT="/usr/share/nginx/html"  # Nginx 网站根目录
NGINX_CONF_DIR="/usr/local/nginx/conf"  # Nginx 配置目录
NGINX_BIN="/usr/local/nginx/sbin/nginx"  # Nginx 二进制文件路径

# 证书路径配置
CERT_BASE_DIR="/etc/letsencrypt/live"  # Let's Encrypt 证书基础目录（默认路径）

# 创建日志目录
mkdir -p "$SCRIPT_DIR/logs"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

error_log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1" | tee -a "$ERROR_LOG"
}

# 检查 certbot 是否安装
check_certbot() {
    if ! command -v certbot &> /dev/null; then
        log "安装 certbot..."
        # CentOS 8 安装 certbot
        sudo dnf install -y epel-release
        sudo dnf install -y certbot python3-certbot-nginx
        if [ $? -ne 0 ]; then
            error_log "certbot 安装失败"
            exit 1
        fi
        log "certbot 安装成功"
    else
        log "certbot 已安装"
    fi
}

# 检查域名配置文件
check_domains_file() {
    if [ ! -f "$DOMAINS_FILE" ]; then
        log "创建域名配置文件: $DOMAINS_FILE"
        cat > "$DOMAINS_FILE" << EOF
# 域名配置文件
# 格式: 域名:配置文件路径
# 每行一个域名配置，用冒号分隔域名和对应的 Nginx 配置文件路径
# 示例:
# example.com:/usr/local/nginx/conf/conf.d/example.conf
# www.example.com:/usr/local/nginx/conf/conf.d/www.conf
# api.example.com:/usr/local/nginx/conf/conf.d/api.conf
EOF
        error_log "请编辑 $DOMAINS_FILE 文件，添加需要申请证书的域名配置"
        exit 1
    fi
}

# 读取域名配置
get_domain_configs() {
    while IFS= read -r line; do
        # 跳过注释行和空行
        if [[ ! "$line" =~ ^[[:space:]]*# ]] && [[ -n "$line" ]]; then
            if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
                local domain="${BASH_REMATCH[1]}"
                local config_file="${BASH_REMATCH[2]}"
                echo "$domain:$config_file"
            else
                error_log "无效的域名配置格式: $line (应为 域名:配置文件路径)"
            fi
        fi
    done < "$DOMAINS_FILE"
}

# 获取所有域名列表
get_domains() {
    local domains=()
    while IFS= read -r line; do
        if [[ "$line" =~ ^([^:]+): ]]; then
            domains+=("${BASH_REMATCH[1]}")
        fi
    done < <(get_domain_configs)
    echo "${domains[@]}"
}

# 获取域名的配置文件路径
get_domain_config_file() {
    local target_domain="$1"
    while IFS= read -r line; do
        if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
            local domain="${BASH_REMATCH[1]}"
            local config_file="${BASH_REMATCH[2]}"
            if [[ "$domain" == "$target_domain" ]]; then
                echo "$config_file"
                return 0
            fi
        fi
    done < <(get_domain_configs)
    return 1
}

# 从 Nginx 配置文件中读取证书路径
get_cert_path_from_nginx_config() {
    local config_file="$1"
    
    if [ -f "$config_file" ]; then
        # 查找 ssl_certificate 配置行
        local cert_line=$(grep -E "^\s*ssl_certificate\s+" "$config_file" | head -1)
        if [ -n "$cert_line" ]; then
            # 提取证书文件路径
            local cert_file=$(echo "$cert_line" | sed -E 's/^\s*ssl_certificate\s+([^;]+);.*/\1/')
            # 返回证书目录（去掉文件名）
            echo "$(dirname "$cert_file")"
            return 0
        fi
    fi
    return 1
}

# 从 Nginx 配置文件中读取 webroot 路径
get_webroot_from_nginx_config() {
    local config_file="$1"
    
    if [ -f "$config_file" ]; then
        # 查找所有 root 配置行
        local root_lines=$(grep -E "^\s*root\s+" "$config_file")
        
        if [ -n "$root_lines" ]; then
            # 优先选择 location / 块中的 root 配置
            local main_root=""
            local other_roots=""
            
            # 读取配置文件，分析 location 块
            local in_location_slash=false
            local line_num=0
            while IFS= read -r line; do
                ((line_num++))
                # 检查是否进入 location / 块（支持多种格式）
                if echo "$line" | grep -qE "location\s*/\s*\{|location\s*/\s*$"; then
                    in_location_slash=true
                    continue
                fi
                
                # 检查是否离开 location 块
                if echo "$line" | grep -q "^\s*}"; then
                    in_location_slash=false
                    continue
                fi
                
                # 如果在 location / 块中且找到 root 配置
                if [ "$in_location_slash" = true ] && echo "$line" | grep -q "^\s*root\s"; then
                    main_root=$(echo "$line" | sed -E 's/^\s*root\s+([^;]+);.*/\1/')
                    break
                fi
            done < "$config_file"
            
            # 如果没有找到 location / 中的 root，使用第一个 root
            if [ -z "$main_root" ]; then
                main_root=$(echo "$root_lines" | head -1 | sed -E 's/^\s*root\s+([^;]+);.*/\1/')
            fi
            
            if [ -n "$main_root" ]; then
                echo "$main_root"
                return 0
            fi
        fi
    fi
    return 1
}

# 从 Nginx 配置文件中读取证书文件路径
get_cert_files_from_nginx_config() {
    local config_file="$1"
    
    if [ -f "$config_file" ]; then
        # 查找 ssl_certificate 和 ssl_certificate_key 配置行
        local cert_line=$(grep -E "^\s*ssl_certificate\s+" "$config_file" | head -1)
        local key_line=$(grep -E "^\s*ssl_certificate_key\s+" "$config_file" | head -1)
        
        if [ -n "$cert_line" ] && [ -n "$key_line" ]; then
            # 提取证书文件路径
            local cert_file=$(echo "$cert_line" | sed -E 's/^\s*ssl_certificate\s+([^;]+);.*/\1/')
            local key_file=$(echo "$key_line" | sed -E 's/^\s*ssl_certificate_key\s+([^;]+);.*/\1/')
            echo "$cert_file:$key_file"
            return 0
        fi
    fi
    return 1
}

# 获取域名的证书路径
get_domain_cert_path() {
    local domain="$1"
    
    # 首先尝试从 Nginx 配置文件中读取
    local config_file=$(get_domain_config_file "$domain")
    if [ -n "$config_file" ]; then
        local cert_path=$(get_cert_path_from_nginx_config "$config_file")
        if [ $? -eq 0 ] && [ -n "$cert_path" ]; then
            echo "$cert_path"
            return 0
        fi
    fi
    
    # 如果无法从配置文件读取，使用默认 Let's Encrypt 路径
    echo "$CERT_BASE_DIR/$domain"
}

# 获取域名的 webroot 路径
get_domain_webroot() {
    local domain="$1"
    
    # 首先尝试从 Nginx 配置文件中读取
    local config_file=$(get_domain_config_file "$domain")
    if [ -n "$config_file" ]; then
        local webroot_path=$(get_webroot_from_nginx_config "$config_file")
        if [ $? -eq 0 ] && [ -n "$webroot_path" ]; then
            echo "$webroot_path"
            return 0
        fi
    fi
    
    # 如果无法从配置文件读取，使用默认 webroot 路径
    echo "$WEBROOT"
}

# 拷贝证书到 Nginx 证书路径
copy_certificates_to_nginx() {
    local domain="$1"
    
    # Let's Encrypt 证书源路径
    local source_cert_dir="$CERT_BASE_DIR/$domain"
    
    if [ ! -d "$source_cert_dir" ]; then
        error_log "源证书目录不存在: $source_cert_dir"
        return 1
    fi
    
    # 获取域名的 Nginx 配置文件
    local config_file=$(get_domain_config_file "$domain")
    if [ -z "$config_file" ]; then
        error_log "无法获取域名 $domain 的 Nginx 配置文件"
        return 1
    fi
    
    # 从 Nginx 配置文件中读取证书文件路径
    local cert_files_info=$(get_cert_files_from_nginx_config "$config_file")
    if [ $? -ne 0 ] || [ -z "$cert_files_info" ]; then
        error_log "无法从 Nginx 配置文件中读取证书文件路径: $config_file"
        return 1
    fi
    
    # 解析证书文件路径
    local target_cert_file=$(echo "$cert_files_info" | cut -d: -f1)
    local target_key_file=$(echo "$cert_files_info" | cut -d: -f2)
    
    # 创建目标目录
    local target_cert_dir=$(dirname "$target_cert_file")
    local target_key_dir=$(dirname "$target_key_file")
    
    sudo mkdir -p "$target_cert_dir"
    if [ $? -ne 0 ]; then
        error_log "创建目标证书目录失败: $target_cert_dir"
        return 1
    fi
    
    if [ "$target_cert_dir" != "$target_key_dir" ]; then
        sudo mkdir -p "$target_key_dir"
        if [ $? -ne 0 ]; then
            error_log "创建目标密钥目录失败: $target_key_dir"
            return 1
        fi
    fi
    
    # 拷贝证书文件
    local copy_success=true
    
    # 拷贝证书文件 (fullchain.pem -> target_cert_file)
    local source_cert_file="$source_cert_dir/fullchain.pem"
    if [ -f "$source_cert_file" ]; then
        sudo cp "$source_cert_file" "$target_cert_file"
        if [ $? -eq 0 ]; then
            log "已拷贝证书文件到 $target_cert_file"
            sudo chmod 644 "$target_cert_file"
            sudo chown root:root "$target_cert_file"
        else
            error_log "拷贝证书文件失败: $target_cert_file"
            copy_success=false
        fi
    else
        error_log "源证书文件不存在: $source_cert_file"
        copy_success=false
    fi
    
    # 拷贝私钥文件 (privkey.pem -> target_key_file)
    local source_key_file="$source_cert_dir/privkey.pem"
    if [ -f "$source_key_file" ]; then
        sudo cp "$source_key_file" "$target_key_file"
        if [ $? -eq 0 ]; then
            log "已拷贝私钥文件到 $target_key_file"
            sudo chmod 600 "$target_key_file"
            sudo chown root:root "$target_key_file"
        else
            error_log "拷贝私钥文件失败: $target_key_file"
            copy_success=false
        fi
    else
        error_log "源私钥文件不存在: $source_key_file"
        copy_success=false
    fi
    
    if [ "$copy_success" = true ]; then
        log "域名 $domain 的证书已成功拷贝到 Nginx 配置路径"
        return 0
    else
        error_log "域名 $domain 的证书拷贝过程中出现错误"
        return 1
    fi
}


# 检查证书是否存在
check_certificate_exists() {
    local domain="$1"
    local cert_path="$CERT_BASE_DIR/$domain"
    
    if [ -d "$cert_path" ] && [ -f "$cert_path/fullchain.pem" ] && [ -f "$cert_path/privkey.pem" ]; then
        return 0  # 证书存在
    else
        return 1  # 证书不存在
    fi
}

# 获取证书的修改时间
get_certificate_mtime() {
    local domain="$1"
    local cert_path="$CERT_BASE_DIR/$domain/fullchain.pem"
    
    if [ -f "$cert_path" ]; then
        stat -c %Y "$cert_path" 2>/dev/null || echo "0"
    else
        echo "0"
    fi
}

# 申请或续期证书（自动判断）
apply_certificates() {
    local mode="$1"  # "auto", "new" 或 "renew"
    local domains=($(get_domains))
    
    if [ ${#domains[@]} -eq 0 ]; then
        error_log "没有找到有效的域名配置"
        return 1
    fi
    
    log "开始处理证书，域名: ${domains[*]}"
    
    local success_count=0
    local total_count=${#domains[@]}
    local new_cert_count=0
    local renew_cert_count=0
    
    for domain in "${domains[@]}"; do
        local action=""
        local certbot_cmd=""
        
        # 自动判断模式：检查证书是否存在
        if [ "$mode" = "auto" ]; then
            if check_certificate_exists "$domain"; then
                action="renew"
                log "域名 $domain 证书已存在，执行续期操作..."
            else
                action="new"
                log "域名 $domain 证书不存在，执行申请操作..."
            fi
        else
            action="$mode"
            if [ "$mode" = "new" ]; then
                log "为域名 $domain 申请证书..."
            else
                log "续期域名 $domain 的证书..."
            fi
        fi
        
        if [ "$action" = "new" ]; then
            # 申请新证书
            ((new_cert_count++))
            
            # 获取该域名的 webroot 路径
            local domain_webroot=$(get_domain_webroot "$domain")
            log "使用 webroot 路径: $domain_webroot"
            
            # 检查 webroot 目录是否存在
            if [ ! -d "$domain_webroot" ]; then
                error_log "webroot 目录不存在: $domain_webroot"
                continue
            fi
            
            # 构建 certbot 命令 - 申请新证书
            certbot_cmd="sudo certbot certonly --webroot -w $domain_webroot --email $EMAIL --agree-tos --non-interactive -d $domain"
            
        else
            # 续期证书
            ((renew_cert_count++))
            
            # 检查证书是否存在
            local cert_path="$CERT_BASE_DIR/$domain"
            if [ ! -d "$cert_path" ]; then
                error_log "域名 $domain 的证书目录不存在: $cert_path"
                continue
            fi
            
            # 记录续期前的证书修改时间
            local cert_mtime_before=$(get_certificate_mtime "$domain")
            
            # 使用 certbot renew 续期特定域名
            # 如果证书还有超过30天才过期，certbot 不会续期
            # 可以使用 --force-renewal 强制续期（仅用于测试）
            certbot_cmd="sudo certbot renew --cert-name $domain"
        fi
        
        # 执行证书操作
        eval $certbot_cmd
        local result=$?
        
        if [ $result -eq 0 ]; then
            if [ "$action" = "new" ]; then
                log "域名 $domain 证书申请成功"
                ((success_count++))
            else
                # 检查证书是否真的被更新了
                local cert_mtime_after=$(get_certificate_mtime "$domain")
                if [ "$cert_mtime_after" -gt "$cert_mtime_before" ]; then
                    log "域名 $domain 证书续期成功（证书已更新）"
                    ((success_count++))
                else
                    log "域名 $domain 证书无需续期（证书未过期或已是最新）"
                    ((success_count++))
                fi
            fi
        else
            if [ "$action" = "new" ]; then
                error_log "域名 $domain 证书申请失败，退出码: $result"
            else
                error_log "域名 $domain 证书续期失败，退出码: $result"
            fi
            continue
        fi
        
        # 证书申请/续期成功后，拷贝证书到 Nginx 证书路径
        copy_certificates_to_nginx "$domain"
        if [ $? -ne 0 ]; then
            error_log "域名 $domain 的证书拷贝失败"
        else
            log "域名 $domain 的证书已拷贝到 Nginx 配置路径"
        fi
    done
    
    # 输出统计信息
    if [ $success_count -eq $total_count ]; then
        if [ $new_cert_count -gt 0 ] && [ $renew_cert_count -gt 0 ]; then
            log "所有域名证书处理成功 (申请: $new_cert_count, 续期: $renew_cert_count)"
        elif [ $new_cert_count -gt 0 ]; then
            log "所有域名证书申请成功 ($new_cert_count 个)"
        else
            log "所有域名证书续期成功 ($renew_cert_count 个)"
        fi
        return 0
    elif [ $success_count -gt 0 ]; then
        log "部分域名证书处理成功 ($success_count/$total_count)"
        return 1
    else
        error_log "所有域名证书处理失败"
        return 1
    fi
}

# 重载 Nginx 配置
reload_nginx() {
    log "重载 Nginx 配置..."
    
    # 测试 Nginx 配置
    sudo "$NGINX_BIN" -t
    if [ $? -ne 0 ]; then
        error_log "Nginx 配置测试失败"
        return 1
    fi
    
    # 检查 Nginx 进程是否在运行
    if pgrep -f "nginx" > /dev/null; then
        # 使用 nginx -s reload 重载配置
        sudo "$NGINX_BIN" -s reload
        if [ $? -eq 0 ]; then
            log "Nginx 重载成功"
            return 0
        else
            error_log "Nginx 重载失败"
            return 1
        fi
    else
        error_log "Nginx 服务未运行，无法重载配置"
        return 1
    fi
}

# 检查证书有效期
check_certificate_expiry() {
    local domains=($(get_domains))
    local expired_domains=()
    
    for domain in "${domains[@]}"; do
        # 首先尝试从 Nginx 配置文件中读取证书文件路径
        local config_file=$(get_domain_config_file "$domain")
        local cert_file=""
        
        if [ -n "$config_file" ]; then
            local cert_files_info=$(get_cert_files_from_nginx_config "$config_file")
            if [ $? -eq 0 ] && [ -n "$cert_files_info" ]; then
                cert_file=$(echo "$cert_files_info" | cut -d: -f1)
            fi
        fi
        
        # 如果无法从 Nginx 配置读取，尝试 Let's Encrypt 路径
        if [ -z "$cert_file" ]; then
            local cert_path=$(get_domain_cert_path "$domain")
            cert_file="$cert_path/fullchain.pem"
        fi
        
        if [ -f "$cert_file" ]; then
            # 获取证书的颁发日期和到期日期
            local not_before=$(openssl x509 -startdate -noout -in "$cert_file" | cut -d= -f2)
            local not_after=$(openssl x509 -enddate -noout -in "$cert_file" | cut -d= -f2)
            
            # 计算剩余天数
            local expiry_timestamp=$(date -d "$not_after" +%s)
            local current_timestamp=$(date +%s)
            local days_until_expiry=$(( (expiry_timestamp - current_timestamp) / 86400 ))
            
            # 格式化日期显示
            local formatted_start=$(date -d "$not_before" '+%Y-%m-%d %H:%M:%S')
            local formatted_end=$(date -d "$not_after" '+%Y-%m-%d %H:%M:%S')
            
            log "域名 $domain 证书信息："
            log "  颁发日期: $formatted_start"
            log "  到期日期: $formatted_end"
            log "  剩余天数: $days_until_expiry 天"
            log "  证书文件: $cert_file"
            
            # 如果证书在30天内过期，标记为需要续期
            if [ $days_until_expiry -lt 30 ]; then
                expired_domains+=("$domain")
            fi
        else
            error_log "域名 $domain 的证书文件不存在: $cert_file"
        fi
    done
    
    if [ ${#expired_domains[@]} -gt 0 ]; then
        log "以下域名证书即将过期，需要续期: ${expired_domains[*]}"
        return 1
    else
        log "所有证书都在有效期内"
        return 0
    fi
}

# 发送通知（可选）
send_notification() {
    local subject="$1"
    local message="$2"
    
    # 如果有邮件配置，可以发送邮件通知
    if command -v mail &> /dev/null; then
        echo "$message" | mail -s "$subject" "$EMAIL"
    fi
    
    # 也可以发送到系统日志
    logger -t "ssl-auto-renew" "$subject: $message"
}

# 主函数
main() {
    log "=== SSL 证书自动更新开始 ==="
    
    # 检查必要工具
    check_certbot
    
    # 检查域名配置
    check_domains_file
    
    # 检查证书状态
    if check_certificate_expiry; then
        log "所有证书都在有效期内，无需续期"
    else
        log "发现即将过期的证书，开始处理..."
        if apply_certificates "auto"; then
            log "证书处理成功，重载 Nginx..."
            if reload_nginx; then
                log "SSL 证书自动更新完成"
                send_notification "SSL证书更新成功" "所有证书已成功处理并重载 Nginx"
            else
                error_log "Nginx 重载失败"
                send_notification "SSL证书更新失败" "证书处理成功但 Nginx 重载失败"
                exit 1
            fi
        else
            error_log "证书处理失败"
            send_notification "SSL证书更新失败" "证书处理失败，请检查日志"
            exit 1
        fi
    fi
    
    log "=== SSL 证书自动更新结束 ==="
}

# 脚本入口
case "$1" in
    "check")
        check_certificate_expiry
        ;;
    "apply")
        mode="$2"
        if [ -z "$mode" ] || [ "$mode" != "auto" ] && [ "$mode" != "new" ] && [ "$mode" != "renew" ]; then
            echo "用法: $0 apply {auto|new|renew}"
            echo "  auto  - 自动判断（推荐）"
            echo "  new   - 申请新证书"
            echo "  renew - 续期现有证书"
            exit 1
        fi
        check_certbot
        check_domains_file
        apply_certificates "$mode"
        if [ $? -eq 0 ]; then
            log "证书操作成功"
            reload_nginx
        fi
        ;;
    "force-renew")
        check_certbot
        check_domains_file
        log "强制续期所有证书..."
        sudo certbot renew --force-renewal
        if [ $? -eq 0 ]; then
            log "强制续期成功，开始拷贝证书..."
            domains=($(get_domains))
            for domain in "${domains[@]}"; do
                copy_certificates_to_nginx "$domain"
            done
            reload_nginx
        else
            error_log "强制续期失败"
        fi
        ;;
    "reload")
        reload_nginx
        ;;
    "copy-certs")
        check_domains_file
        log "开始拷贝证书到 Nginx 证书路径..."
        local copy_success=true
        local domains=($(get_domains))
        
        for domain in "${domains[@]}"; do
            copy_certificates_to_nginx "$domain"
            if [ $? -ne 0 ]; then
                error_log "域名 $domain 的证书拷贝失败"
                copy_success=false
            fi
        done
        
        if [ "$copy_success" = true ]; then
            log "所有证书已成功拷贝到对应的 Nginx 证书路径"
        else
            error_log "部分证书拷贝失败，请检查日志"
        fi
        ;;
    "list-domains")
        echo "已配置的域名："
        while IFS= read -r line; do
            if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
                domain="${BASH_REMATCH[1]}"
                config_file="${BASH_REMATCH[2]}"
                cert_path=$(get_domain_cert_path "$domain")
                echo "  域名: $domain"
                echo "  配置文件: $config_file"
                echo "  证书路径: $cert_path"
                echo ""
            fi
        done < <(get_domain_configs)
        ;;
    "show-cert-paths")
        echo "证书路径配置："
        echo "  默认证书目录: $CERT_BASE_DIR"
        echo ""
        echo "各域名证书路径："
        while IFS= read -r line; do
            if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
                domain="${BASH_REMATCH[1]}"
                config_file="${BASH_REMATCH[2]}"
                cert_path=$(get_domain_cert_path "$domain")
                
                # 检查是否从 Nginx 配置文件读取
                nginx_cert_path=$(get_cert_path_from_nginx_config "$config_file")
                if [ $? -eq 0 ] && [ -n "$nginx_cert_path" ]; then
                    echo "  $domain -> $cert_path (从 Nginx 配置读取)"
                else
                    echo "  $domain -> $cert_path (使用默认路径)"
                fi
            fi
        done < <(get_domain_configs)
        ;;
    "test-cert-files")
        echo "测试从 Nginx 配置文件读取证书文件路径："
        while IFS= read -r line; do
            if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
                domain="${BASH_REMATCH[1]}"
                config_file="${BASH_REMATCH[2]}"
                
                echo "域名: $domain"
                echo "配置文件: $config_file"
                
                if [ -f "$config_file" ]; then
                    echo "配置文件存在，尝试读取证书文件路径..."
                    cert_files_info=$(get_cert_files_from_nginx_config "$config_file")
                    if [ $? -eq 0 ] && [ -n "$cert_files_info" ]; then
                        target_cert_file=$(echo "$cert_files_info" | cut -d: -f1)
                        target_key_file=$(echo "$cert_files_info" | cut -d: -f2)
                        echo "  证书文件: $target_cert_file"
                        echo "  私钥文件: $target_key_file"
                        echo "  证书目录: $(dirname "$target_cert_file")"
                        echo "  私钥目录: $(dirname "$target_key_file")"
                    else
                        echo "  未找到 ssl_certificate 或 ssl_certificate_key 配置"
                    fi
                else
                    echo "  配置文件不存在"
                fi
                echo ""
            fi
        done < <(get_domain_configs)
        ;;
    "test-multi-root")
        echo "测试多路径配置的 root 选择："
        while IFS= read -r line; do
            if [[ "$line" =~ ^([^:]+):(.+)$ ]]; then
                domain="${BASH_REMATCH[1]}"
                config_file="${BASH_REMATCH[2]}"
                
                echo "域名: $domain"
                echo "配置文件: $config_file"
                
                if [ -f "$config_file" ]; then
                    echo "配置文件存在，分析所有 root 路径："
                    
                    # 显示所有 root 配置
                    echo "  所有 root 配置："
                    grep -n "^\s*root\s+" "$config_file" | while read -r line; do
                        echo "    $line"
                    done
                    
                    # 显示 location 块分析
                    echo "  location 块分析："
                    in_location_slash=false
                    line_num=0
                    while IFS= read -r config_line; do
                        ((line_num++))
                        # 检查是否进入 location / 块
                        if echo "$config_line" | grep -qE "location\s*/\s*\{|location\s*/\s*$"; then
                            echo "    第 $line_num 行: 进入 location / 块"
                            in_location_slash=true
                        elif echo "$config_line" | grep -q "^\s*}"; then
                            if [ "$in_location_slash" = true ]; then
                                echo "    第 $line_num 行: 离开 location / 块"
                            fi
                            in_location_slash=false
                        elif [ "$in_location_slash" = true ] && echo "$config_line" | grep -q "^\s*root\s+"; then
                            root_path=$(echo "$config_line" | sed -E 's/^\s*root\s+([^;]+);.*/\1/')
                            echo "    第 $line_num 行: 在 location / 块中找到 root: $root_path"
                        fi
                    done < "$config_file"
                    
                    # 显示选择的 root 路径
                    selected_root=$(get_webroot_from_nginx_config "$config_file")
                    if [ $? -eq 0 ] && [ -n "$selected_root" ]; then
                        echo "  选择的 root 路径: $selected_root"
                        if [ -d "$selected_root" ]; then
                            echo "  目录存在: 是"
                            echo "  目录权限: $(ls -ld "$selected_root" | awk '{print $1}')"
                        else
                            echo "  目录存在: 否"
                        fi
                    else
                        echo "  未找到合适的 root 配置"
                    fi
                else
                    echo "  配置文件不存在"
                fi
                echo ""
            fi
        done < <(get_domain_configs)
        ;;
    *)
        echo "用法: $0 {check|apply|force-renew|reload|copy-certs|list-domains|show-cert-paths|test-cert-files|test-multi-root}"
        echo "  check                - 检查证书有效期"
        echo "  apply {auto|new|renew} - 统一的证书操作方法（auto=自动判断）"
        echo "  force-renew          - 强制续期所有证书（用于测试）"
        echo "  reload               - 重载 Nginx 配置"
        echo "  copy-certs           - 将证书拷贝到 Nginx 证书路径"
        echo "  list-domains         - 列出所有已配置的域名"
        echo "  show-cert-paths      - 显示证书路径配置"
        echo "  test-cert-files      - 测试从 Nginx 配置文件读取证书文件路径"
        echo "  test-multi-root      - 测试多路径配置的 root 选择"
        exit 1
        ;;
esac
